package com.example.ymm.modules1.service.dd.ms;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkoauth2_1_0.models.CreateJsapiTicketResponse;
import com.aliyun.dingtalkoauth2_1_0.models.CreateJsapiTicketResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.example.ymm.bo.RedisService;
import com.example.ymm.exception.YmException;
import com.example.ymm.util.RedisKeyManager;
import com.example.ymm.util.RedisUtil;
import com.example.ymm.util.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class JsapiH5Service {


    @Autowired
    AccessTokenH5Service2 accessTokenH5Service;
    @Autowired
    RedisUtil redisUtil;
    @Value("${dd_h5.agentId}")
    private String agentId;


    public  com.aliyun.dingtalkoauth2_1_0.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }

    public String getRequestJsapi()  {

        String accessToken = accessTokenH5Service.getAccessToken();

        String jsapiTicket=null;

        com.aliyun.dingtalkoauth2_1_0.models.CreateJsapiTicketHeaders createJsapiTicketHeaders = new com.aliyun.dingtalkoauth2_1_0.models.CreateJsapiTicketHeaders();
        createJsapiTicketHeaders.xAcsDingtalkAccessToken = accessToken;
        try {
            com.aliyun.dingtalkoauth2_1_0.Client client = createClient();
            CreateJsapiTicketResponse response = client.createJsapiTicketWithOptions(createJsapiTicketHeaders, new RuntimeOptions());
            CreateJsapiTicketResponseBody body = response.getBody();
            if(response.getStatusCode().equals(200)){
                Long expireIn = body.getExpireIn();
                jsapiTicket = body.getJsapiTicket();


                redisUtil.setIfAbsent(RedisKeyManager.h5_jsapi_key,jsapiTicket,expireIn-100, TimeUnit.SECONDS);
            }

        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                throw new YmException(err.message);
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                throw new YmException(err.message);
            }

        }
        return jsapiTicket;
    }


    public String getJsapiTicket(){
        String jsapiTicket=null;
        String ticket= redisUtil.get(RedisKeyManager.h5_jsapi_key,String.class);
        if(UtilValidate.isNotEmpty(ticket)){
            jsapiTicket=ticket;
        }else{
            String requestJsapi = getRequestJsapi();
            if(UtilValidate.isNotEmpty(requestJsapi)){
                jsapiTicket=requestJsapi;
            }
        }
        return jsapiTicket;
    }

    public JSONObject getConfig(String url){
        String jsapiTicket = getJsapiTicket();
        String nonceStr="heng_li_h5";
        long timeStamp=new Date().getTime();
//        url="http://220.161.77.66:10111/";
        String sign =null;

        try {
            sign = DdConfigSign.sign(jsapiTicket, nonceStr, timeStamp, url);
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        //System.out.println("--sign:"+sign);
        JSONObject json=new JSONObject();
        json.put("timeStamp",timeStamp);
        json.put("url",url);
        json.put("corpId","ding2e2011827f67ec7d35c2f4657eb6378f");
        json.put("signature",sign);
        json.put("agentId",agentId);
        return json;
    }


}
